######## Run the complete script to load the function #########

sug_conc <- function(Concentration, Sugar, From, To){
  df <- data.frame(Sugar = c("Sucrose", "Glucose", "Fructose"),
                   mr = c(342.3, 180.155, 180.155),
                   a1 = c(0.998709, 0.998442, 0.998371),
                   a2 = c(3.7430e-3, 3.7390e-3, 3.8550e-3),
                   a3 = c(1.7639e-5, 1.5410e-5, 1.5230e-5),
                   b1 = c(0.998138, 0.998226, 0.998253),
                   b2 = c(3.8765e-3, 3.8084e-3, 3.9021e-3),
                   b3 = c(-1.8716e-6, -1.9924e-6, -2.2878e-6))
  if(sum(c("Sucrose", "Glucose", "Fructose") %in% Sugar) != 1){
    stop ("No valid sugar entered, please use just one of 'Sucrose', 'Glucose' or 'Fructose'")
  } else if (sum(c("w/w", "w/v", "M") %in% From) != 1){
    stop ("'From' must be one of 'w/w', 'w/v' or 'M'")
  } else if (sum(c("w/w", "w/v", "M") %in% To) != 1){
    stop ("'To' must be one of 'w/w', 'w/v' or 'M'")
  }
  if(From == To){
    return (Concentration)
  } else {
    params <- df[df$Sugar == Sugar,]
    z <- ((From == "M") * Concentration * (df$mr[df$Sugar == Sugar]) / 10 +
            (From == "w/w") * (Concentration * (params$a1 + params$a2 * Concentration + params$a3 * Concentration^2)) + 
            (From == "w/v") * Concentration)
    y <- ((To == "M") * z * 10 / (df$mr[df$Sugar == Sugar]) + 
            (To == "w/w") * (z / (params$b1 + params$b2 * z + params$b3 * z^2)) +
            (To == "w/v") * z)
  }
  if(max(z) > 130){
    warning ("Concentration(s) outside expected range, check values; extrapolation errors may occur")
  }
  if(min(z) < 0){
    stop ("Concentration(s) must be positive number(s)")
  }
  if(min(z) < 1){
    warning ("Conversion may be inaccurate for concentrations < 1% w/v")
  }
  y
}


#Example:

sug_conc(c(10, 20, 30, 40, 50, 60, 70, 80), "Sucrose", "w/w", "w/v")



